package com.base.cn.platform.os.controller.mobile.user.login;

import com.base.cn.platform.os.common.MobileBaseController;
import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.rsa.WebRsaUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.action.ActionKey;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.LoginForm;
import com.base.cn.platform.os.common.utils.user.UserExpandFrom;
import com.base.cn.platform.os.common.utils.web.DeviceUtils;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralService;
import com.base.cn.platform.os.service.manage.user.login.UserLoginService;
import com.base.cn.platform.os.service.manage.user.sms.UserSendSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 用户登录Controller
 *
 * @author s.li
 * @create 2018-06-06-18:59
 */
@Controller
@RequestMapping("/mobile/user")
public class MobileUserLoginController extends MobileBaseController {

    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserSendSmsService userSendSmsService;
    @Autowired
    private LoginUserData loginUserData;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    @Autowired
    private CusUserIntegralService cusUserIntegralService;

    /**
     * 用户注册页面
     * @return
     */
    @RequestMapping("/register")
    public String register(Model model,@RequestParam(value = "invitationKey",required = false,defaultValue = "") String invitationKey ) throws Exception{
        Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
        model.addAttribute("invitationKey",invitationKey);
        model.addAttribute("keyMap",keyMap);
        return resultPage("/user/login/register");
    }

    /**
     * 查看协议
     * @return String
     */
    @RequestMapping("/toProtocolPageView")
    public String toProtocolPageView(Model model){
        TreeMap<String, String> sysConfigContextOnOff = sysConfigService.getSysConfigContext(ConfigName.PROTOCOL);
        model.addAttribute("content",sysConfigContextOnOff.get("content"));
        return resultPage("/user/login/protocol");
    }

    /**
     * 用户登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login(@RequestParam(value = "message",required = false) String message,
                        HttpServletRequest request, Model model) throws Exception{
        boolean isWeChat = DeviceUtils.isWeChat(request);
        TreeMap<String, String> sysConfigContextOnOff = sysConfigService.getSysConfigContext(ConfigName.ONOFF);
        TreeMap<String, String> sysConfigContextInFo = sysConfigService.getSysConfigContext(ConfigName.INFO);
        model.addAttribute("weiXinLoginSwitch",sysConfigContextOnOff.get("weiXinLoginSwitch"));
        model.addAttribute("qqLoginSwitch",sysConfigContextOnOff.get("qqLoginSwitch"));
        model.addAttribute("titleName",sysConfigContextInFo.get("appName"));
        model.addAttribute("isWeChat",isWeChat);
        model.addAttribute("message",message);
        Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
        model.addAttribute("keyMap",keyMap);
        //如果登录了则去主页
        if(webMobileLoginUtil.isLogin(request)){
            return redirect(request,"/mobile/index");
        }
        return resultPage("/user/login/login");
    }

    /**
     * 注册用户
     *
     * @param request HttpServletRequest
     * @param mobile  手机号
     * @param mobileCode  手机验证码
     * @param password  密码
     * @param confirmPwd  确认密码
     */
    @RequestMapping("/doRegister")
    @ResponseBody
    public Map<String, Object> doRegister(HttpServletRequest request, HttpServletResponse response,
                                          @RequestParam("mobile")String mobile,
                                          @RequestParam("mobileCode")String mobileCode,
                                          @RequestParam("password")String password,
                                          @RequestParam("confirmPwd")String confirmPwd,
                                          @RequestParam("sign") String sign,@RequestParam(value = "invitationKey",defaultValue = "",required = false) String invitationKey)throws Exception {
        Map<String,Object> user = new HashMap<>();
        user.put("mobile",mobile);
        user.put("mobileCode",mobileCode);
        user.put("password",password);
        user.put("confirmPwd",confirmPwd);
            //检查是否有分享邀请
       if(StringUtils.isNotEmpty(invitationKey)){
                user.put("inviteKey",invitationKey);
        }
        //获取当前IP的地址
        //user.put("regAddress",WebUtils.getIpToAddressStr(request));
        user.put("registerFrom", UserExpandFrom.mobileFrom.getKey());
        user.put("sign", sign);
        Map<String,Object> resultMap =userLoginService.toRegister(user,LoginForm.LOGIN_FROM_MOBILE);
        resultMap = loginUserData.setUserData(request,response,resultMap);
        if(!ResultUtil.getSuccess(resultMap)){//如果登录失败，则重新获取密钥
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }
        return resultMap;
    }

    /**
     * 执行登录
     * @return Map<String,Object>
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public Map<String,Object> doLogin(HttpServletRequest request,
                                      HttpServletResponse response,
                                      @RequestParam("loginAccount") String loginAccount,
                                      @RequestParam("password")String password,
                                      @RequestParam("sign") String sign) throws Exception{
        Map<String,Object> params=new HashMap<>();
        params.put("loginAccount",loginAccount);
        params.put("password",password);
        params.put("sign",sign);
        Map<String,Object> resultMap = userLoginService.userLogin(params, LoginForm.LOGIN_FROM_MOBILE,"false",null,null);
        resultMap = loginUserData.setUserData(request,response,resultMap);

        if(!ResultUtil.getSuccess(resultMap)){//如果登录失败，则重新获取密钥
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }else{
            // 登录成功 添加分享人积分
            String shareKey = WebUtils.getCookie(request, "shareKey");
            if (StringUtils.isNotEmpty(shareKey)) {
                BigDecimal shareUserId= new BigDecimal( shareKey.split("_")[1]);
                cusUserIntegralService.addUserIntegral(ActionKey.SHARE, shareUserId, shareUserId, 0, 2);
            }
        }

        return resultMap;
    }

    /**
     * 判断用户是否登录
     * @param request
     */
    @RequestMapping("/isLogin")
    @ResponseBody
    public Map<String, Object> isLogin(HttpServletRequest request,
                                       HttpServletResponse response){
        boolean isLogin = webMobileLoginUtil.isLogin(request);
        if(isLogin==false){//如果未登录，则缓存当前页面的url
            String requestURL = request.getHeader("referer");
            WebUtils.setCookie(response,CommonConstants.REDIRECT,requestURL,1);
        }
        return ResultUtil.SUCCESS(isLogin);
    }
    //===================================找回密码，开始========================
    /**
     * 找回密码功能
     * @return
     */
    @RequestMapping("/retrievePassword")
    public String retrievePassword(Model model) throws Exception{
        Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
        model.addAttribute("keyMap",keyMap);
        return resultPage("/user/login/forget");
    }

    /**
     * 找回密码-验证手机号
     * @param mobile 手机号
     * @param mobileCode 手机验证码
     * @return Map<String,Object>
     */
    @RequestMapping("/verificationMobileCode")
    @ResponseBody
    public Map<String,Object> verificationMobileCode(@RequestParam("mobile") String mobile,
                                                     @RequestParam("mobileCode") String mobileCode){
        return userLoginService.verificationForgetMobileCode(mobile,mobileCode);
    }

    /**
     * 找回密码
     * @param mobile 手机号
     * @param mobileCode 手机验证码
     * @param password 新密码
     * @param confirmPwd 确认密码
     * @return Map<String, Object>
     */
    @RequestMapping("/ajax/retrievePassword")
    @ResponseBody
    public Map<String, Object> retrieveAjaxPassword(@RequestParam("mobile") String mobile,
                                                    @RequestParam("mobileCode") String mobileCode,
                                                    @RequestParam("password") String password,
                                                    @RequestParam("confirmPwd") String confirmPwd,
                                                    @RequestParam("sign") String sign) throws Exception{
        Map<String,Object> resultMap = userLoginService.retrievePwd(mobile,mobileCode,password,confirmPwd,sign);
        if(!ResultUtil.getSuccess(resultMap)){
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }
        return  resultMap;
    }
    //===================================找回密码，结束========================

    /**
     * 退出登录
     * @param request
     * @return 重定向首页
     */
    @RequestMapping("/outLogin")
    public String outLogin(HttpServletRequest request,HttpServletResponse response){
        String sessionId = WebUtils.getCookie(request,CommonConstants.MOBILE_USER_SINGLE_ID);
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        boolean isOk = userLoginService.signOut(sessionId,userId);
        if(isOk){//删除COOKIE会话
            WebUtils.deleteCookie(request,response,CommonConstants.MOBILE_USER_SINGLE_ID);
        }
        return redirect(request,"/mobile/index");
    }
    //=============================================完善资料，开始==================================================
    /**
     * 完善专业页面
     * @param model
     * @param sessionId
     * @return
     */
    @RequestMapping("/perfectSubject")
    public String perfectSubject(Model model,
                                 @RequestParam("key") String sessionId){
        model.addAttribute("sessionId",sessionId);
        return resultPage("/user/perfect/perfect-subject");
    }

    /**
     * 完善手机号页面
     * @param model
     * @param sessionId
     * @return
     */
    @RequestMapping("/perfectMobile")
    public String perfectMobile(Model model,
                                @RequestParam("key") String sessionId){
        model.addAttribute("sessionId",sessionId);
        return resultPage("/user/perfect/perfect-mobile");
    }

    /**
     * 设置学员专业
     * @param sessionId 用户缓存KEY
     * @param parentId 专业ID
     * @param childIds 科目ID串
     * @return Map<String,Object>
     */
    @RequestMapping("/setUserSubjectIds")
    @ResponseBody
    public Map<String,Object> setUserSubjectIds(HttpServletRequest request,HttpServletResponse response,
                                    @RequestParam("sessionId") String sessionId,
                                    @RequestParam("parentId") BigDecimal parentId,
                                    @RequestParam("childIds") String childIds){
        Map<String,Object> resultMap = userLoginService.setUserSubjectIds(sessionId,parentId,childIds,"false",LoginForm.LOGIN_FROM_MOBILE);
        return loginUserData.setUserData(request,response,resultMap);
    }

    /**
     * 设置用户手机号
     * @param sessionId 缓存KEY
     * @param mobile 手机号
     * @param mobileCode 手机验证码
     * @return Map<String,Object>
     */
    @RequestMapping("/setUserMobile")
    @ResponseBody
    public Map<String,Object> setUserMobile(HttpServletRequest request,HttpServletResponse response,
                                @RequestParam("sessionId") String sessionId,
                                @RequestParam("mobile") String mobile,
                                @RequestParam("mobileCode") String mobileCode){
        Map<String,Object> resultMap = userLoginService.setUserMobile(sessionId,mobile,mobileCode,"false",LoginForm.LOGIN_FROM_MOBILE);
        return loginUserData.setUserData(request,response,resultMap);
    }
    //=============================================完善资料，结束==================================================

    /**
     * 手机发送验证码
     * @param mobile 手机号
     * @param status 类型，1注册，找回，3绑定，4更换，5完善资料
     * @param sessionId  是否是第三方登录，true是，false否
     * @return Map<String ,Object>
     */
    @RequestMapping("/ajax/sendMobileMsg")
    @ResponseBody
    public Map<String, Object> sendMobileMsg(@RequestParam("mobile") String mobile,
                                             @RequestParam("status") int status,
                                             @RequestParam(value = "sessionId",required = false) String sessionId) {
        if(status!=1 && status!=2 && status!=5){
            return ResultUtil.ERROR("数据错误，短信发送失败");
        }
        return userSendSmsService.sendMobileCode(mobile,status,sessionId);
    }

}
